package biz.yfsoft.app.fastframework.admin;

import java.io.File;
import java.io.IOException;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.core.document.Document;
import biz.yfsoft.app.fastframework.core.document.DocumentSaveHex;
import biz.yfsoft.app.fastframework.jfinal.extra.BytesRender;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;


/**
 * 平台中进行文档的管理
 * @author YFsoft
 *
 */
public class AttachmentController extends AdminController {
	
	@Override
	protected String getTable() {
		return "sys_file";
	}

	
	public void index() {
		render("/admin/attachment.jsp");
	}
	
	@Override
	protected String getSearchFields(String searchs) {
		if(searchs == null){
			return " 1 = 1 ";
		}
		return " name like '%{key}%' ".replace("{key}", searchs);
	}
	
	public void upload() {
		UploadFile upFile = getFile("file");
		Bo record = null;
		try {
			record = Document.me().saveSync(upFile);
		} catch (DocumentSaveHex e) {
			renderJson(wrapJson(-1,e.getMessage()));
			return;
		}
		
		renderJson(wrapJson(0,"",record.toJson()));
	}
	
	/**
	 * 下载文档附件
	 */
	public void download() {
		//获取到文档的id
		String id = getPara(0);
		//读取到文档的信息
		Record record = Db.findById(getTable(), Integer.parseInt(id));
		//文档名称
		String name = record.getStr("name");
		//文档的存储模式
		String mode = record.getStr("mode");
		String path = record.getStr("path");
		File f = new File(path);
		if(f.exists()){
			//如果缓存文件还存在，则直接下载
			renderFile(new File(path));
			return;
		}
		if("LOCAL".equals(mode)){
			//本地化的存储
			//通过path的路径来进行文件的下载
			renderFile(new File(path));
		}else{
			try {
				//通过header进行跳转
				byte[] data = Document.me().loadToMemory(Integer.parseInt(id));
				render(new BytesRender(name,data));
				return;
			} catch (IOException e) {
				renderText("您要搜索的文档不存在!");
				return;
			}
			
		}
		renderText("您要搜索的文档不存在!");
		
	}
	
	
}
